package handlers

import (
	"restaurant-system/config"
	"restaurant-system/internal/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 获取用户积分
func GetUserPoints(c *gin.Context) {
	userID, _ := c.Get("userID")
	var user models.User
	if err := config.DB.First(&user, userID).Error; err != nil {
		c.JSON(404, gin.H{"error": "用户不存在"})
		return
	}

	c.JSON(200, gin.H{"points": user.Points})
}

// 获取用户积分历史
func GetPointRecords(c *gin.Context) {
	userID, _ := c.Get("userID")
	var records []models.PointRecord

	if err := config.DB.Where("user_id = ?", userID).Order("created_at desc").Find(&records).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取积分记录失败"})
		return
	}

	c.JSON(200, gin.H{"records": records})
}

// 使用积分
type UsePointsRequest struct {
	Points  int     `json:"points" binding:"required,min=1"`
	OrderID uint    `json:"order_id" binding:"required"`
	Amount  float64 `json:"amount" binding:"required"`
}

func UsePoints(c *gin.Context) {
	userID, _ := c.Get("userID")
	var req UsePointsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 开启事务
	tx := config.DB.Begin()

	// 检查用户积分是否足够
	var user models.User
	if err := tx.First(&user, userID).Error; err != nil {
		tx.Rollback()
		c.JSON(404, gin.H{"error": "用户不存在"})
		return
	}

	if user.Points < req.Points {
		tx.Rollback()
		c.JSON(400, gin.H{"error": "积分不足"})
		return
	}

	// 扣减积分
	if err := tx.Model(&user).Update("points", user.Points-req.Points).Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "扣减积分失败"})
		return
	}

	// 记录积分使用
	record := models.PointRecord{
		UserID:  userID.(uint),
		OrderID: &req.OrderID,
		Points:  -req.Points,
		Type:    "use",
		Amount:  req.Amount,
		Remark:  "订单抵扣",
	}

	if err := tx.Create(&record).Error; err != nil {
		tx.Rollback()
		c.JSON(500, gin.H{"error": "创建积分记录失败"})
		return
	}

	tx.Commit()
	c.JSON(200, gin.H{"message": "使用积分成功", "remaining_points": user.Points - req.Points})
}

// 订单完成后增加积分
func AddOrderPoints(orderID uint, userID uint, amount float64) error {
	tx := config.DB.Begin()

	// 获取积分规则
	var rule models.PointRule
	if err := tx.Where("type = ?", "consume").First(&rule).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 计算获得的积分
	points := int(amount * rule.Rate)

	// 更新用户积分
	if err := tx.Model(&models.User{}).Where("id = ?", userID).
		Update("points", gorm.Expr("points + ?", points)).Error; err != nil {
		tx.Rollback()
		return err
	}

	// 记录积分获得
	record := models.PointRecord{
		UserID:  userID,
		OrderID: &orderID,
		Points:  points,
		Type:    "consume",
		Amount:  amount,
		Remark:  "消费获得积分",
	}

	if err := tx.Create(&record).Error; err != nil {
		tx.Rollback()
		return err
	}

	return tx.Commit().Error
}
